var install = require("./lib/install.js");
var down = require("./lib/down.js");
var executeRecord = require("./executeRecord.js");

let utils = {};
utils.BROADCAST_APP_PROGRESS = "BROADCAST_APP_PROGRESS";
utils.BROADCAST_APP_NAME = "BROADCAST_APP_NAME";
utils.BROADCAST_GLOBAL_PROGRESS = "BROADCAST_GLOBAL_PROGRESS";
utils.BROADCAST_SCRIPT_FINISH = "BROADCAST_SCRIPT_FINISH";
utils.BROADCAST_SCRIPT_RETRY = "BROADCAST_SCRIPT_RETRY";
utils.BROADCAST_SCRIPT_EXIT = "BROADCAST_SCRIPT_EXIT";

//脚本完成
utils.scriptFinish = function(){
    events.broadcast.emit(this.BROADCAST_SCRIPT_FINISH);
    
}
//脚本重试
utils.scriptRetry = function(errorMsg){
    events.broadcast.emit(this.BROADCAST_SCRIPT_RETRY, errorMsg);
    
}
//脚本退出
utils.scriptExit = function(errorMsg){
    events.broadcast.emit(this.BROADCAST_SCRIPT_EXIT, errorMsg);
    
}


//更新app名字
utils.updateAppName = function (appName) {
    events.broadcast.emit(this.BROADCAST_APP_NAME, appName);
}
//更新app 进度
utils.updateAppProgress = function (progress) {
    if (progress >= 100) {
        progress = 100;
        //脚本完成
        this.scriptFinish();
    }
    if (progress < 0) {
        progress = 0;
    }
    events.broadcast.emit(this.BROADCAST_APP_PROGRESS, progress);
    
}
//更新全局进度
utils.updateGlobalProgress = function (progress) {
    events.broadcast.emit(this.BROADCAST_GLOBAL_PROGRESS, progress);
}

//获取版本
utils.getVersion = function (pkg) {
    try {
        let manager = context.getPackageManager()
        let info = manager.getPackageInfo(pkg, 0);
        return info.versionName;
    } catch (error) {
        toastLog("获取安装包错误:" + pkg)
    }
    return "1.0"; //TODO 圆圆来处理
};
//真实点击
utils.realClick = function (btn) {
    click(btn.bounds().centerX(), btn.bounds().centerY());
}
/**
 * 向上滑动
 */
utils.swip_up = function () {
    var w = device.width
    var h = device.height

    function bezier_curves(cp, t) {
        cx = 3.0 * (cp[1].x - cp[0].x);
        bx = 3.0 * (cp[2].x - cp[1].x) - cx;
        ax = cp[3].x - cp[0].x - cx - bx;
        cy = 3.0 * (cp[1].y - cp[0].y);
        by = 3.0 * (cp[2].y - cp[1].y) - cy;
        ay = cp[3].y - cp[0].y - cy - by;

        tSquared = t * t;
        tCubed = tSquared * t;
        result = { "x": 0, "y": 0 };
        result.x = (ax * tCubed) + (bx * tSquared) + (cx * t) + cp[0].x;
        result.y = (ay * tCubed) + (by * tSquared) + (cy * t) + cp[0].y;
        return result;
    };


    function sml_move(qx, qy, zx, zy, time) {
        //仿真随机带曲线滑动: qx, qy, zx, zy, time 代表起点x,起点y,终点x,终点y,过程耗时单位毫秒
        var xxy = [time];
        var point = [
            { "x": qx, "y": qy },
            { "x": random(qx - 100, qx + 100), "y": random(qy, qy + 50) },
            { "x": random(zx - 100, zx + 100), "y": random(zy, zy + 50) },
            { "x": zx, "y": zy }
        ];
        for (let i = 0; i < 1; i += 0.08) {
            xxyy = [parseInt(bezier_curves(point, i).x), parseInt(bezier_curves(point, i).y)]
            xxy.push(xxyy);
        }
        gesture.apply(null, xxy);
    }

    sml_move(w / 2, h * 0.8 + h * random() * 0.1, w / 2, h * 0.15, 200 + 600 * random());
}

/**
 * 向下滑动
 */
utils.swip_down = function () {
    var w = device.width
    var h = device.height

    function bezier_curves(cp, t) {
        cx = 3.0 * (cp[1].x - cp[0].x);
        bx = 3.0 * (cp[2].x - cp[1].x) - cx;
        ax = cp[3].x - cp[0].x - cx - bx;
        cy = 3.0 * (cp[1].y - cp[0].y);
        by = 3.0 * (cp[2].y - cp[1].y) - cy;
        ay = cp[3].y - cp[0].y - cy - by;

        tSquared = t * t;
        tCubed = tSquared * t;
        result = { "x": 0, "y": 0 };
        result.x = (ax * tCubed) + (bx * tSquared) + (cx * t) + cp[0].x;
        result.y = (ay * tCubed) + (by * tSquared) + (cy * t) + cp[0].y;
        return result;
    };


    function sml_move(qx, qy, zx, zy, time) {
        //仿真随机带曲线滑动: qx, qy, zx, zy, time 代表起点x,起点y,终点x,终点y,过程耗时单位毫秒
        var xxy = [time];
        var point = [
            { "x": qx, "y": qy },
            { "x": random(qx - 100, qx + 100), "y": random(qy, qy + 50) },
            { "x": random(zx - 100, zx + 100), "y": random(zy, zy + 50) },
            { "x": zx, "y": zy }
        ];
        for (let i = 0; i < 1; i += 0.08) {
            xxyy = [parseInt(bezier_curves(point, i).x), parseInt(bezier_curves(point, i).y)]
            xxy.push(xxyy);
        }
        gesture.apply(null, xxy);
    }

    sml_move(w / 2, h * 0.15, w / 2, h * 0.8 + h * random() * 0.1, 200 + 600 * random());
}


//最近查找
utils.near = function (base, nearSelect, layer) {
    var _base = base;
    var result = null;
    var _layer = 0;
    while (_base.parent()) {
        _layer++;
        if (_layer >= layer) {
            //达到最大查找深度
            return null;
        }
        _base = _base.parent();
        result = _base.findOne(nearSelect);
        if (result) {
            return result;
        }
    }
    return result;
}
utils.openScreenCapture = function () {
    let thread1 = threads.start(function () {
        toastLog("检查请求截屏!")
        var began = text("立即开始").findOne();
        if (began) {
            sleep(1000)
            toastLog("发现请求截屏！");
            began.click();
            sleep(1000);
            thread1.interrupt();
        }
    });
    sleep(1000);
    if (!requestScreenCapture()) {
        toastLog("请求截图失败!");
        exit();
    }
    else {
        toastLog("请求截图成功!");
    }
}
utils.launchAppEnhance = function (app_name) {
    let thread = threads.start(function () {
        toastLog("检查是否有打开权限!")
        while (true) {
            var allow = text("允许").findOne(5000)
            if (allow) {
                sleep(1000)
                toastLog("发现允许授权!")
                allow.click()
                sleep(1000)
                thread.interrupt()
                break
            }
        }
    })
    sleep(1000)
    var result = launchApp(app_name)
    sleep(3000)
    thread.interrupt()
    return result
}

//等待currentActivity改变
utils.waitActivityChange = function (timeoutFun) {
    var cur = currentActivity();
    var i = 0;
    while (cur === currentActivity()) {
        i++;
        if (i >= 30) {
            if (timeoutFun) {
                if (timeoutFun()) {
                    i = 0;
                    continue;
                } else {
                    return;
                }
            }
        }
        sleep(2000);
    }
}
//等待广告
utils.waitAdvert = function (finalActivity) {
    sleep(10000); //延迟5s 防止页面还未切换
    var adActivity = currentActivity();
    while (currentActivity() !== finalActivity) {
        console.log("waitAdvert.currentActivity:", currentActivity(), ",finalActivity:", finalActivity);
        if(currentActivity() === "com.kwad.sdk.api.proxy.app.KsRewardVideoActivity"){
            while (currentActivity() !== finalActivity) {
                back();
                sleep(2000);
                var close = id("ksad_end_close_btn").findOne(2000);
                if(close){
                    close.click();
                    sleep(2000);
                }
            }
            return;
        }
        if (currentActivity() === "com.qq.e.ads.RewardvideoPortraitADActivity") {
            while (currentActivity() !== finalActivity) {
                var close = className("android.widget.ImageView").clickable().depth(5).drawingOrder(2).findOne(2000);
                if (close) {
                    console.log("广告关闭成功:", currentActivity());
                    close.click();
                    sleep(2000);
                }
                close = id("ksad_end_close_btn").findOne(2000);
                if(close){
                    close.click();
                    sleep(2000);
                }
            }
            return;
        }
        if (currentActivity() === "com.bytedance.sdk.openadsdk.activity.base.TTRewardVideoActivity") {
            while (currentActivity() !== finalActivity) {
                var close = id("tt_video_ad_close_layout").clickable().findOne(2000);
                if (close) {
                    console.log("广告关闭成功:", currentActivity());
                    close.click();
                    return;
                }
                sleep(2000);
                back();
            }
            return;
        }
        if (currentActivity() === "com.bytedance.sdk.openadsdk.activity.TTRewardExpressVideoActivity") {
            while (currentActivity() !== finalActivity) {
                back();
                sleep(2000);
                close = text("继续试玩").clickable().findOne(2000);
                if (close) {
                    console.log("广告关闭成功:", currentActivity());
                    close.click();
                    sleep(1000);
                }


                var 试玩游戏 = text("试玩游戏 领取奖励").findOne(2000);
                if (试玩游戏) {
                    sleep(500);
                    //关闭后 可以查找到 tt_video_ad_close_layout 按钮
                    this.realClick(试玩游戏);
                    sleep(500);
                    // continue;
                }
                var close = id("tt_video_ad_close_layout").clickable().findOne(2000);
                if (close) {
                    console.log("广告关闭成功:", currentActivity());
                    close.click();
                    sleep(1000);
                }
                
            }
            return;
        }
        if (currentActivity() === "com.bytedance.sdk.openadsdk.activity.base.TTRewardExpressVideoActivity") {
            while (currentActivity() !== finalActivity) {
                back();
                sleep(2000);
                close = text("继续试玩").clickable().findOne(2000);
                if (close) {
                    console.log("广告关闭成功:", currentActivity());
                    close.click();
                    sleep(1000);
                }


                var 试玩游戏 = text("试玩游戏 领取奖励").findOne(2000);
                if (试玩游戏) {
                    sleep(500);
                    //关闭后 可以查找到 tt_video_ad_close_layout 按钮
                    this.realClick(试玩游戏);
                    sleep(500);
                    // continue;
                }


                var close = id("tt_video_ad_close_layout").clickable().findOne(2000);
                if (close) {
                    console.log("广告关闭成功:", currentActivity());
                    close.click();
                    sleep(1000);
                }
            }
            return;
        }
        if (currentActivity() === "com.sigmob.sdk.base.common.AdActivity") {
            log("-------");
            while (currentActivity() !== finalActivity) {
                var close = className("android.widget.ImageView").depth(5).drawingOrder(1).findOne(2000);
                if (close) {
                    log("关闭...");
                    utils.realClick(close);
                    sleep(1000);
                }
            }
            return;
        }
        if (currentActivity() === "com.android.systemui.recents.RecentsActivity") {
            //TODO 界面异常 报警?
            console.log("关闭广告失败.页面异常...");
            // return;
        }
        back();
        sleep(2000);
    }
    // while (true) {
    //     for(var i = 0; i < this._closeAdvertAction.length; i++){
    //         var item = this._closeAdvertAction[i];
    //         var advert = item.select();
    //         if(advert){
    //             toastLog("发现广告");
    //             if(item.action){
    //                 item.action(advert);
    //             }else{
    //                 this._defaultClickAction(advert);
    //                 return;
    //             }

    //         }
    //     }
    //     sleep(2000);
    // }
}

//获取版本
utils.getVersion = function (pkg) {
    try {
        let manager = context.getPackageManager()
        let info = manager.getPackageInfo(pkg, 0);
        return info.versionName;
    } catch (error) {
        toastLog("获取安装包错误:" + pkg)
    }
    return "1.0"; //TODO 圆圆来处理
};

//{ 0: '已安装', 1: '需更新',   2: '下载'}
utils.versionDiff = function (remoteVersion, localVersion) {
    var remoteVersionInt = parseInt(remoteVersion.replace(/[^0-9]/ig, ""));
    var localVersionInt = parseInt(localVersion.replace(/[^0-9]/ig, ""));
    if (localVersionInt >= remoteVersionInt) {
        return 0;
    } else {
        return 1;
    }


    if (remoteVersion == localVersion) {
        return 0;
    }
    if (remoteVersion.indexOf(".") == -1 && localVersion.indexOf(".") == -1) {
        return parseInt(remoteVersion) > parseInt(localVersion) ? 1 : 0;
    }
    let $_s = remoteVersion.split('.'), $_c = localVersion.split('.');
    let $len = Math.min($_s.length, $_c.length);
    for (var i = 0; i < $len; i++) {
        if ($_s[i].length != $_c[i].length) {
            return $_s[i].length > $_c[i].length ? 1 : -1;
        }
        if (parseInt($_s[i]) == parseInt($_c[i])) {
            continue;
        }
        return parseInt($_s[i]) > parseInt($_c[i]) ? 1 : -1;
    }
    return 0;
}

utils.downloadAndInstall = function (label, url, pkg) {
    let apkPath = files.join(app.PATH.APKS, label + ".apk");


    let ex = new java.util.concurrent.Exchanger();
    toast("开始下载" + label);
    console.log("开始下载" + label);
    let d = dialogs.build({
        title: label + "下载中",
        progress: {
            max: 100,
            horizontal: true
        }
    });
    // d.setProgress(50)
    // console.log("d", d)
    // ui.run(function () {

    // })
    d.show();
    down.download(url, apkPath, function (total, cur) {
        if (cur == total) {
            // ui.run(function () {

            // })
            d.cancel();
            // data.text = "下载完成";
            toast(label + "下载完成");
            console.log(label + "下载完成");
            console.log("apkPath:", apkPath)
            install(apkPath, pkg);
            try { text('完成').findOne(400).click(); } catch (e) { }
            toast(label + "安装完成");
            console.log(label + "安装完成");
            ex.exchange(null);
        } else {
            var ratio = ((cur / total) * 100).toFixed(2)
            d.setProgress(ratio)
            // ui.run(function () {
            //     data.text = ratio + "%";
            //     // btn.setText(ratio + "%");
            // })
        }


    });
    ex.exchange(null);
}




/**
 * 离线脚本更新
 */
utils.download_scripts = function(script_name) {
    let current_path = files.cwd();
    let dist_path = files.join(current_path, "/" + script_name+".js");
    let script_name_without_suffix = script_name.replace(".js", "");
    if(files.exists(dist_path)) {
        files.remove(dist_path);
    }
    try{
        log("脚本目录：" + dist_path)
        let res = http.get("https://gitee.com/asst_tech/gdt_hb/raw/master/" + script_name + ".js");
        files.write(dist_path, res.body.string(), encoding = "utf-8");
        log(script_name_without_suffix + "更新成功!");
    }
    catch(error){
        toastLog("更新失败：" + error);
    }

}




log(utils.versionDiff("1.1.1", "1.1.2"));

module.exports = utils;